// page/unit/cropper/index.js
let app = getApp();
let config = require('../../../config.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    croWidth: "0", // canvas 裁剪的宽度
    croHeight: "0", // canvas 裁剪的高度
    checkImage: "", // 设置头像选中的图片路径
    origCoords: { x: 0, y: 0 }, // canvas 左上角坐标
    startCroCoords: { x: 0, y: 0 }, // 开始移动触摸坐标
    iscropper: false // 是否开始移动裁剪头像

  },
  // 触摸裁剪区域，初始化移动裁剪区
  startCropper: function (ev) {
    // console.log('startCropper', ev.changedTouches[0]);
    let startCroCoords = this.data.startCroCoords;
    startCroCoords.x = ev.changedTouches[0].pageX;
    startCroCoords.y = ev.changedTouches[0].pageY;
    this.setData({
      iscropper: true,
      startCroCoords: startCroCoords
    })
  },
  // 移动裁剪区，计算相应坐标
  moveCropper: function (ev) {
    // console.log('moveCropper', ev);
    if (!this.data.iscropper) { return }
    let croWidth = parseInt(this.data.croWidth);
    let croHeight = parseInt(this.data.croHeight);
    let startCroCoords = this.data.startCroCoords;
    let origCoords = this.data.origCoords;
    let currentPage = {
      x: ev.changedTouches[0].pageX,
      y: ev.changedTouches[0].pageY
    }
    let x = origCoords.x + currentPage.x - startCroCoords.x;
    let y = origCoords.y + currentPage.y - startCroCoords.y;
    if (x <= 0) {
      x = 0;
    } else if (x >= croWidth - 120) {
      x = croWidth - 120
    }
    if (y <= 0) {
      y = 0
    } else if (y >= croHeight - 120) {
      y = croHeight - 120
    }

    this.setData({
      origCoords: {
        x: x,
        y: y
      },
      startCroCoords: currentPage
    })
    let src = this.data.checkImage;

    let context = wx.createCanvasContext('cropper');
    context.drawImage(src, -origCoords.x, -origCoords.y, croWidth, croHeight);
    context.draw();
  },
  // 结束触摸屏幕，绘制裁剪区域图片，并设置头像
  endCropper: function (ev) {
  },
  // 确定裁剪结果，并设置为头像
  confirmCropper: function (ev) {
    let that = this;
    // 保存绘制的图片内容
    wx.canvasToTempFilePath({
      canvasId: 'cropper',
      success: function (res) {
        console.log('canvasToTempFilePath', res);
        
        wx.uploadFile({
          url: config.settingUrl+'saveflag.php',
          filePath: res.tempFilePath,
          name:'flag',
          formData: {
            'usid': app.userInfo.usid
          },
          success:function(res){
            let rdata = res.data;
            if (typeof rdata !== 'object') {
              rdata = JSON.parse(rdata.replace("\ufeff", ""));
            }
            console.log('flag',rdata);
            if(rdata.stats===0){
              wx.showToast({
                title: res.data.msg,
              })
              return;
            }
            that.setData({
              iscropper: false,
              issetFlag: false,
              origCoords: { x: 0, y: 0 },
              showBigFlag: false,
              previewImage: ""
            })
            // 同步到全局账号信息中
            let app = getApp();
            app.userInfo.flag = rdata.flag;
            wx.redirectTo({
              url: '/page/unit/userInfo/index'
            })
          }
        })
      }
    });
  },
  // 取消设置头像
  cancelCropper: function (ev) {
    this.setData({
      iscropper: false,
      showBigFlag: false,
      issetFlag: false,
      showCanvas: false
    });
    wx.redirectTo({
      url: '/page/unit/userInfo/index'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    let src = options.imgPaths;
    let that = this;
    that.setData({
      checkImage: src
    })
    wx.getImageInfo({
      src: src,
      success: function (res) {
        // console.log("getImageInfo",res)
        if (!app.systemInfo.windowWidth){
          app.getSystemInfo();
        }
        let widthRatio = app.systemInfo.windowWidth / res.width;
        that.setData({
          issetFlag: true,
          croWidth: app.systemInfo.windowWidth + "px",
          croHeight: res.height * widthRatio + "px"
        });

        // 绘制初始化图片
        let context = wx.createCanvasContext('cropper');
        context.drawImage(src, 0, 0, app.systemInfo.windowWidth, res.height * widthRatio);
        context.draw();
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})